/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.brain.cobranza.mbean;

import com.brain.cobranza.dto.AsigCarteraDto;
import com.brain.cobranza.dto.CargaDto;
import com.brain.cobranza.dto.DeudaClienteDto;
import com.brain.cobranza.manager.AsigCarteraCargaManager;
import com.brain.cobranza.manager.AsigCarteraGestorManager;
import com.brain.cobranza.manager.AsigCarteraManager;
import com.brain.cobranza.manager.CargaManager;
import com.brain.cobranza.manager.DeudaClienteManager;
import com.brain.core.common.UtilCore;
import com.brain.core.configuracion.WebServletContextListener;
import com.brain.core.exception.DAOException;
import com.brain.core.view.mbean.*;
import com.brain.core.manager.BitacoraManager;
import com.brain.core.manager.RecursosManager;
import com.brain.segu.dto.UsuarioDto;
import com.brain.segu.manager.UsuarioManager;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import javax.annotation.Resource;
import javax.faces.model.SelectItem;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

/**
 *
 * @author Indra
 */
@Controller("asigCarteraMBean")
@Scope("session")
public class AsigCarteraMBean extends GenericMBean implements Serializable {

    private static Logger logger = Logger.getLogger(AsigCarteraMBean.class);
    @Resource
    private AsigCarteraManager manager;
    @Resource
    private AsigCarteraCargaManager asigCargaManager;
    @Resource
    private AsigCarteraGestorManager gestorManager;
    @Resource
    private BitacoraManager bitacoraManager;
    @Resource
    private RecursosManager recursosManager;
    @Resource
    private DeudaClienteManager deudaClienteManager;
    @Autowired
    private ApplicationMBean applicationMBean;
    @Autowired
    private SessionMBean sessionMBean;
    private List<AsigCarteraDto> lista;
    private AsigCarteraDto dto;
    private AsigCarteraDto dtoFiltro;
    private String keyEntidad = "key.entidad.asig.cartera";
    private SelectItem[] siTiposEstado;
    private List<CargaDto> listaCargas;
    private List<UsuarioDto> listaGestores;
    private CargaDto[] selectedCargas;
    private UsuarioDto[] selectedGestores;
    private SelectItem[] tipoCartera;

    public AsigCarteraMBean() {
        this.dtoFiltro = new AsigCarteraDto();
    }

    public String iniciar() {
        this.lista = null;
        this.dto = null;
        this.listaCargas = null;
        this.listaGestores = null;
        this.selectedCargas = null;
        this.selectedGestores = null;
        this.dtoFiltro = new AsigCarteraDto();
        return manager.getUrlLista();
    }

    public String nuevo() {
        sessionMBean.setAccion(applicationMBean.getNuevo());
        sessionMBean.setTitulo(recursosManager.construirTitulo(keyEntidad, sessionMBean.getAccion()));
        this.dto = manager.inicializar();
        return manager.getUrl();
    }

    public String editar() {
        sessionMBean.setAccion(applicationMBean.getEditar());
        sessionMBean.setTitulo(recursosManager.construirTitulo(keyEntidad, sessionMBean.getAccion()));
        try {
            this.dto = manager.obtenerPorId(this.dto.getId());
        } catch (DAOException ex) {
            logger.error(ex);
        }

        return manager.getUrl();
    }

    public String ver() {
        sessionMBean.setAccion(applicationMBean.getVer());
        sessionMBean.setTitulo(recursosManager.construirTitulo(keyEntidad, sessionMBean.getAccion()));
        try {
            this.dto = manager.obtenerPorId(this.dto.getId());
        } catch (DAOException ex) {
            logger.error(ex);
        }
        return manager.getUrl();
    }

    public void buscar() {
        try {
            this.lista = this.manager.obtener(this.dtoFiltro);
        } catch (DAOException ex) {
            showError("ERROR_SISTEMA", ex.getMessage());
            logger.error(ex);
        }
    }

    public void anularCartera() throws DAOException {
        List<DeudaClienteDto> deudaClienteList = new ArrayList<DeudaClienteDto>();
        if (dto.getListaCarga() != null) {
            
            for (int i = 0; i < dto.getListaCarga().size(); i++) {
                try {
                    deudaClienteList = deudaClienteManager.obtenerDeudasAsociadas(dto.getListaCarga().get(i).getCargaClienteDto().getId());
                } catch (DAOException ex) {
                    logger.error(ex.getMessage());
                }
                if (deudaClienteList.size() != 0) {
                    for (int j = 0; j < deudaClienteList.size(); j++) {
                        deudaClienteList.get(j).setEstado(recursosManager.obtenerParametroPorID(828L));
                        deudaClienteManager.editar(deudaClienteList.get(j));
                    }
                }
            }
            dto.setEstado("I");
        }
        
        this.manager.guardar(dto);
    }
    
     public void terminarCartera() throws DAOException {
        List<DeudaClienteDto> deudaClienteList = new ArrayList<DeudaClienteDto>();
        if (dto.getListaCarga() != null) {
            for (int i = 0; i < dto.getListaCarga().size(); i++) {
                try {
                    deudaClienteList = deudaClienteManager.obtenerDeudasAsociadas(dto.getListaCarga().get(i).getCargaClienteDto().getId());
                } catch (DAOException ex) {
                    logger.error(ex.getMessage());
                }
                if (deudaClienteList.size() != 0) {
                    for (int j = 0; j < deudaClienteList.size(); j++) {
                        deudaClienteList.get(j).setEstado(recursosManager.obtenerParametroPorID(829L));
                        deudaClienteManager.editar(deudaClienteList.get(j));
                    }
                }
            }
            dto.setEstado("T");
        }
        
        this.manager.guardar(dto);
    }

    public String guardar() {
        if (this.selectedCargas.length != 0 && this.selectedGestores.length != 0) {
            manager.guardar(this.dto);
            guardarDetalle();
        } else {
            showError(UtilCore.Internacionalizacion.getMensajeInternacional("cartera.seleccionar.un.registro"));
            return null;
        }
        return editar();
    }

    public void guardarDetalle() {
        sessionMBean.setAccionDetalle(applicationMBean.getNuevo());
        try {
            List<AsigCarteraDto> l = this.manager.obtenerTodos();
            Long maxId = this.manager.obtenerMaxId(l);
            AsigCarteraDto aDto = this.manager.obtenerPorId(maxId);
            this.asigCargaManager.guardarCargas(aDto, this.selectedCargas);
            this.gestorManager.guardarGestores(aDto, this.selectedGestores);
            List<DeudaClienteDto> deudaClienteList = new ArrayList<DeudaClienteDto>();
            for (int i = 0; i < selectedCargas.length; i++) {
                if (dto.getTipoAsignacion().equals("D")) {
                    deudaClienteList = deudaClienteManager.obtenerDeudasAsociadas(selectedCargas[i].getId());
                } else if (dto.getTipoAsignacion().equals("M")) {
                    deudaClienteList = deudaClienteManager.obtenerDeudasAsociadasOrdenDeuda(selectedCargas[i].getId());
                }
                if (!deudaClienteList.isEmpty()) {
                    deudaClienteManager.asignarDeudas(deudaClienteList, selectedGestores);
                }
            }
        } catch (DAOException e) {
            showError("ERROR_SISTEMA", e.getMessage());
            logger.error(e);
        }
    }

    public String verBitacora() {
        bitacoraManager.cargarBitacoraEntidad(manager.getIdEntidad(), this.dto.getId());
        return null;
    }

    public String retroceder() {
        buscar();
        return manager.getUrlLista();
    }

    public void cancelar() {
        sessionMBean.setAccion(applicationMBean.getEditar());
        this.dto.setEstado("C");
        this.manager.guardar(dto);
    }

        public void procesar() throws DAOException {
        List<DeudaClienteDto> deudaClienteList = new ArrayList<DeudaClienteDto>();
        if (dto.getListaCarga() != null) {
            
            for (int i = 0; i < dto.getListaCarga().size(); i++) {
                try {
                    deudaClienteList = deudaClienteManager.obtenerDeudasAsociadas(dto.getListaCarga().get(i).getCargaClienteDto().getId());
                } catch (DAOException ex) {
                    logger.error(ex.getMessage());
                }
                if (deudaClienteList.size() != 0) {
                    for (int j = 0; j < deudaClienteList.size(); j++) {
                        deudaClienteList.get(j).setEstado(recursosManager.obtenerParametroPorID(790L));
                        deudaClienteManager.editar(deudaClienteList.get(j));
                    }
                }
            }
            dto.setEstado("P");
        }
        this.manager.guardar(dto);
    }

    /**
     * GETTER AND SETTER*
     */
    public static Logger getLogger() {
        return logger;
    }

    public static void setLogger(Logger logger) {
        AsigCarteraMBean.logger = logger;
    }

    public BitacoraManager getBitacoraManager() {
        return bitacoraManager;
    }

    public void setBitacoraManager(BitacoraManager bitacoraManager) {
        this.bitacoraManager = bitacoraManager;
    }

    public RecursosManager getRecursosManager() {
        return recursosManager;
    }

    public void setRecursosManager(RecursosManager recursosManager) {
        this.recursosManager = recursosManager;
    }

    public ApplicationMBean getApplicationMBean() {
        return applicationMBean;
    }

    public void setApplicationMBean(ApplicationMBean applicationMBean) {
        this.applicationMBean = applicationMBean;
    }

    public SessionMBean getSessionMBean() {
        return sessionMBean;
    }

    public void setSessionMBean(SessionMBean sessionMBean) {
        this.sessionMBean = sessionMBean;
    }

    public List<AsigCarteraDto> getLista() {
        return lista;
    }

    public void setLista(List<AsigCarteraDto> lista) {
        this.lista = lista;
    }

    public AsigCarteraDto getDto() {
        return dto;
    }

    public void setDto(AsigCarteraDto dto) {
        this.dto = dto;
    }

    public AsigCarteraDto getDtoFiltro() {
        return dtoFiltro;
    }

    public void setDtoFiltro(AsigCarteraDto dtoFiltro) {
        this.dtoFiltro = dtoFiltro;
    }

    public String getKeyEntidad() {
        return keyEntidad;
    }

    public void setKeyEntidad(String keyEntidad) {
        this.keyEntidad = keyEntidad;
    }

    public SelectItem[] getSiTiposEstado() {
        this.siTiposEstado = this.manager.siTiposEstado();
        return this.siTiposEstado;
    }

    public void setSiTiposEstado(SelectItem[] siTiposEstado) {
        this.siTiposEstado = siTiposEstado;
    }

    public List<CargaDto> getListaCargas() throws DAOException {
        CargaManager cargManager = (CargaManager) WebServletContextListener.getApplicationContext().getBean("cargaManager");
        this.listaCargas = cargManager.obtenerCargasActivas();
        return this.listaCargas;
    }

    public void setListaCargas(List<CargaDto> listaCargas) {
        this.listaCargas = listaCargas;
    }

    public List<UsuarioDto> getListaGestores() throws DAOException {
        UsuarioManager usuarioManager = (UsuarioManager) WebServletContextListener.getApplicationContext().getBean("usuarioManager");
        this.listaGestores = usuarioManager.obtenerGestoresActivos();
        return this.listaGestores;
    }

    public void setListaGestores(List<UsuarioDto> listaGestores) {
        this.listaGestores = listaGestores;
    }

    public CargaDto[] getSelectedCargas() {
        return selectedCargas;
    }

    public void setSelectedCargas(CargaDto[] selectedCargas) {
        this.selectedCargas = selectedCargas;
    }

    public UsuarioDto[] getSelectedGestores() {
        return selectedGestores;
    }

    public void setSelectedGestores(UsuarioDto[] selectedGestores) {
        this.selectedGestores = selectedGestores;
    }

    public AsigCarteraManager getManager() {
        return manager;
    }

    public void setManager(AsigCarteraManager manager) {
        this.manager = manager;
    }

    public AsigCarteraCargaManager getAsigCargaManager() {
        return asigCargaManager;
    }

    public void setAsigCargaManager(AsigCarteraCargaManager asigCargaManager) {
        this.asigCargaManager = asigCargaManager;
    }

    public AsigCarteraGestorManager getGestorManager() {
        return gestorManager;
    }

    public void setGestorManager(AsigCarteraGestorManager gestorManager) {
        this.gestorManager = gestorManager;
    }

    public SelectItem[] getTipoCartera() {
        SelectItem[] si = new SelectItem[2];
        si[0] = new SelectItem("D", "DEFAULT");
        si[1] = new SelectItem("P", "MAYOR A MENOR");
        return si;
    }

    public void setTipoCartera(SelectItem[] tipoCartera) {
        this.tipoCartera = tipoCartera;
    }

    public DeudaClienteManager getDeudaClienteManager() {
        return deudaClienteManager;
    }

    public void setDeudaClienteManager(DeudaClienteManager deudaClienteManager) {
        this.deudaClienteManager = deudaClienteManager;
    }
}
